#!/usr/bin/env python
"""
Here's some text to describe the utils module
"""


#Import Modules
import os, pygame
from pygame.locals import *
from weakref import WeakKeyDictionary
from events import *
import threading
	

#-----------------------------------------------------------------------------
def DoNothing():
	return

#-----------------------------------------------------------------------------
def load_png(name, extradir=''):
    if isinstance(name, list):
	    fullname = 'data'
	    for component in name:
	    	fullname = os.path.join(fullname, component)
    else:
    	fullname = os.path.join('data', extradir, name)
    try:
        image = pygame.image.load(fullname)
	if image.get_alpha is None:
		image = image.convert()
	else:
		image = image.convert_alpha()
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    return image

#-----------------------------------------------------------------------------
class EventManager:
	"""this object is responsible for coordinating most communication
	between the Model, View, and Controller."""
	def __init__(self ):
		self.listeners = WeakKeyDictionary()
		self.eventQueue= []
		self.lock = threading.RLock()

	#----------------------------------------------------------------------
	def Debug( self, ev):
		return
		if not isinstance( ev, GUIMouseMoveEvent ):
			print "   Message: " + ev.name

	#----------------------------------------------------------------------
	def RegisterListener( self, listener ):
		#if not hasattr( listener, "Notify" ): raise blah blah...
		with self.lock:
			self.listeners[ listener ] = 1

	#----------------------------------------------------------------------
	def UnregisterListener( self, listener ):
		with self.lock:
			if listener in self.listeners.keys():
				del self.listeners[ listener ]
	def Flush( self ):
		self.Post(TickEvent())
		
	#----------------------------------------------------------------------
	def Post( self, event ):
		with self.lock:
			from copy import copy
			if not isinstance(event, TickEvent): 
				self.eventQueue.append( event )
			else:
				events = copy( self.eventQueue )
				self.eventQueue = []
				while len(events) > 0:
					ev = events.pop(0)
					self.Debug( ev )
	
					for listener in self.listeners.keys():
						listener.Notify( ev )
	
				#at the end, notify listeners of the Tick event
				for listener in self.listeners.keys():
					listener.Notify( event )
	


#this calls the 'main' function when this script is executed
if __name__ == '__main__': print "didn't expect that!"
